<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\franchisee\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvmZv8Ui7E8X9dmjLoT5SUZngOe19nV9p4lvo7SgqWEne2P++cXpq7BjZ62dzRdoVyA+jElIzcdEiDwVR2i9yPWMQq8e2s/ToGwKXX1z+873QGqhe8udEQoYJ2oRwq4vtRITDc2KZxkysnFFiCBLTBms8FimzRmylt+tM+ibLG5pUuTY2Vik9k+h79ceSySzE0OFsyNnV1Wi7JxzQfySd9Jjg+VxcjOLQKhJ2LRLCd2QOmRgOFZGvodl/7N/BE03AEzgwieLCC0Owyv7L0W/D3iGmw1It9ZR3fI0FDkDxV/Dxhxy9NWvYlbrtL29PA0CNzQ5hM/ejgPB1QqVC3Cna9wIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhNJ9Q2PcHxZaFrWF1H0zYUadTxzRmXMAt8VVOkEHShNJVUfKoJ9qPmpWjUxJPPODQoLy9OAYY+mgwY4tEuROeBwJ2Ak4/81pl8suP7DLXf1wKKESEVgYJ2q9BCGqv91ZPTgPhdidn/P5Oq3wf/rLfPvrrkvZ2Gknoq1XcRDZdXqYzd9gml/nXPP/p8QG4xazuA+fIY2mSe6OLFzAV1QeCCgtTx4MmLc27b9WdlF5Os+ubZmOemt6m8u/nnoR8CGucuoQIsQzjwXy256dl/mOrz0QTub5Cwa24ga/wReEut/UVaAWuelMBCyr9ebJhjohnURJ1R/x6uRkxUEH8HX8xQIDAQAB",
        'private_key' => 'MIIEpAIBAAKCAQ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lX4ytm6YtQDGKz1O6fp8VNIknQjlSEJeWRsX3CznSmwaoib7ldTmtcP81CQCAx1PVzUS/RzdOSR9wAQ4zWnacTNlxUC0ynU7al4LN/nCWRypCcjHnuBuoYR1W2LUiuUlvIU6msPtz6yAkzb8ywN6W13pVdc6H+8dMCgYEAibZByvoYfKsK5U3ZIK733iempqkiw5a33B/2I8pgYFPCMX55BuT38vDdUOZzUf53qW+smHUtM7TKsgyW5BxEqqlVvchbYwqSEAlkrCFZtii9ZJNTkXoB1yta0T110ojOCBrNPXuDUU4gRbCIjpS0gc9ZIfPOEnmt44Wfgxj8qKUCgYA3flhtfbbNV+QgdmW/lBSlPjuV/qdHnNGVY31N8EVARqeAm7m5x8cqdBsIqTneaKQiNdcEc+Mkf+q0tXXVQuhpEXPl0DatkAN5gWU9Tfe01vjT2/crhDp8Vjhn1xS4UNyZQUgo0hKT84EvpTZKEXCKf+D3qzsjIsL6U9zKVcqf5Q=='
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号

    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//    public function getParam(){
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
        $money = '0.01';
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2021001192604261";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://android.xuanwumobile.com/franchisee/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msg'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msg'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }

    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return string|void
     * user_id：用户ID,
     * type：1 课程购买  2 捐赠  3 打赏
     * price：打赏或捐赠的价格，当type为2或者3时传
     * activity_id：捐赠的活动ID，当type为2时，传此值
     */
    public function alipay()
    {
        extract(input());
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }

        if($params['type']==1){//充值
                $money = input('param.money');//价格
                $money = 0.01;
                $order_number = date('YmdHis') . str_pad(mt_rand(1, 99999999), 6, '0', STR_PAD_LEFT).$user_id;
                $this->body = '小易滴达充值';
                $this->subject = '小易滴达充值';
                $this->total_amount = $money;
                $this->out_trade_no = $order_number;
                //插入订单表
                $data['balance_num'] = $order_number;
                $data['user_id'] = $user_id;
                $data['balance_type'] = 2;
                $data['balance_time'] = date('Y-m-d H:i:s');
                $data['balance_title'] = "余额充值";
                $data['balance_price'] = $money;
                $data['balance_status'] = 1;
                $data['balance_jia_jian'] = 1;
                $data['balance_xs'] = 2;
                $res = Db::table('up_user_balance')->insert($data);
                if($res) {
                    $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
                    return json_encode($respont);
                } else {
                    return json_encode(['status' => 0, 'msg' => '生成订单失败，请联系管理员']);
                }
            }elseif($params['type']==2){//订单支付
                $info = Db::table('up_order')->where('order_id',$params['order_id'])->find();
                $money = $info['order_dzxy_freight'];//价格
                $money = 0.01;
                $this->body = '小易滴达运费定金支付';
                $this->subject = '小易滴达运费定金';
                $this->total_amount = $money;
                $this->out_trade_no = $info['order_num'];
                 if($info['order_id']!=''){
                     $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
                     return json_encode($respont);
                }else{
                     return json_encode(['status' => 0, 'msg' => '生成订单失败，请联系管理员']);
                 }
        }

    }

    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $dataOrder = array();
                $dataOrder['order_paytime1'] = $getInfo['gmt_payment'];//支付时间
                Db::startTrans();
                try{
                    //查询订单表
                    $info = Db::table('up_order')->where('order_num',$num)->find();
                    $info1 =Db::table('up_user_balance')->where('balance_num',$num)->find();
                    if($info['order_id']!=''){//订单支付
                        if($info['order_status']==7){
                            $dataOrder['order_status'] = 8;
                             Db::table('up_order')->where('order_num',$num)->update($dataOrder);
                              //查询地区
                              $go_sheng = Db::table('up_area')->where('district_id',$info['order_go_sheng'])->value('district');
                              $go_shi = Db::table('up_area')->where('district_id',$info['order_go_shi'])->value('district');
                              $to_sheng = Db::table('up_area')->where('district_id',$info['order_to_sheng'])->value('district');
                              $to_shi = Db::table('up_area')->where('district_id',$info['order_to_shi'])->value('district');
                             //插入order_detail表
                             $listData['order_detail_go_sheng'] = $go_sheng;
                             $listData['order_detail_go_shi'] = $go_shi;
                             $listData['order_detail_to_sheng'] = $to_sheng;
                             $listData['order_detail_to_shi'] = $to_shi;
                             $listData['order_detail_incon'] = '';
                             $listData['user_id'] = $info['order_jms_user'];
                             $listData['order_detail_price'] = $info['order_freight'];
                             $listData['order_id'] = $info['order_id'];
                             $listData['order_detail_type'] = 1;
                             $listData['order_detail_ymd'] = $info['order_fb_ymr'];
                             $listData['oder_detail_ym'] = $info['order_fb_ym'];
                             Db::table('up_order_detail')->insertGetId($listData);
                            //司机成本
                            //司机成本
                            $listData1['order_detail_go_sheng'] = $go_sheng;
                            $listData1['order_detail_go_shi'] = $go_shi;
                            $listData1['order_detail_to_sheng'] = $to_sheng;
                            $listData1['order_detail_to_shi'] = $to_shi;
                            $listData1['order_detail_incon'] = '司机成本';
                            $listData1['user_id'] = $info['order_jms_user'];
                            $listData1['order_detail_price'] = $info['order_dzxy_freight'];
                            $listData1['order_id'] = $info['order_id'];
                            $listData1['order_detail_type'] = 2;
                            $listData1['order_detail_ymd'] = $info['order_fb_ymr'];
                            $listData1['oder_detail_ym'] = $info['order_fb_ym'];
                            Db::table('up_order_detail')->insertGetId($listData1);
                            //进税项
                            $listData2['order_detail_go_sheng'] = $go_sheng;
                            $listData2['order_detail_go_shi'] = $go_shi;
                            $listData2['order_detail_to_sheng'] = $to_sheng;
                            $listData2['order_detail_to_shi'] = $to_shi;
                            $listData2['order_detail_incon'] = '进税项';
                            $listData2['user_id'] = $info['order_jms_user'];
                            $listData2['order_detail_price'] = ($info['order_freight']/1.09)*0.09;
                            $listData2['order_id'] = $info['order_id'];
                            $listData2['order_detail_type'] = 2;
                            $listData2['order_detail_ymd'] = $info['order_fb_ymr'];
                            $listData2['oder_detail_ym'] = $info['order_fb_ym'];
                            Db::table('up_order_detail')->insertGetId($listData2);
                            //平台抽成
                              $price3 = 0;
                            if($info['order_freight']<30000){
                                $price3 = $info['order_freight']*0.0358;
                            }elseif ($info['order_freight']>=30000&&$info['order_freight']<300000){
                                $price3 = $info['order_freight']*0.0258;
                            }elseif ($info['order_freight']>=300000){
                                $price3 = $info['order_freight']*0.0198;
                            }
                            $listData3['order_detail_go_sheng'] = $go_sheng;
                            $listData3['order_detail_go_shi'] = $go_shi;
                            $listData3['order_detail_to_sheng'] = $to_sheng;
                            $listData3['order_detail_to_shi'] = $to_shi;
                            $listData3['order_detail_incon'] = '平台抽成';
                            $listData3['user_id'] = $info['order_jms_user'];
                            $listData3['order_detail_price'] = $price3;
                            $listData3['order_id'] = $info['order_id'];
                            $listData3['order_detail_type'] = 2;
                            $listData3['order_detail_ymd'] = $info['order_fb_ymr'];
                            $listData3['oder_detail_ym'] = $info['order_fb_ym'];
                            Db::table('up_order_detail')->insertGetId($listData3);


                            //插入司机钱包明细
                            $order_number = date('YmdHis') . str_pad(mt_rand(1, 99999999), 6, '0', STR_PAD_LEFT).$info['order_dirver_user'];
                            $user_real_name = Db::table('up_u_user')
                                ->where('user_id',$info['order_jms_user'])
                                ->value("user_real_name");
                            $data1['user_id'] = $info['order_dirver_user'];
                            $data1['balance_type'] = 2;
                            $data1['balance_time'] = date('Y-m-d H:i:s');
                            $data1['balance_title'] = "收到加盟商".($user_real_name).'支付运费';
                            $data1['balance_num'] = $order_number;
                            $data1['balance_price'] = $info['order_dzxy_freight'];
                            $data1['balance_status'] = 2;
                            $data1['balance_jia_jian'] = 1;
                            $data1['balance_xs'] = 1;
                            Db::table('up_user_balance')->insertGetId($data1);

                            //定金
                            $data4['user_id'] = $info['order_dirver_user'];
                            $data4['balance_type'] = 2;
                            $data4['balance_time'] = date('Y-m-d H:i:s');
                            $data4['balance_title'] = $go_sheng.$go_shi.'--'.$to_sheng.$to_shi.'订单定金返还';
                            $data4['balance_num'] = $order_number;
                            $data4['balance_price'] = $info['order_dzxy_yf'];
                            $data4['balance_status'] = 2;
                            $data4['balance_jia_jian'] = 1;
                            $data4['balance_xs'] = 1;
                            Db::table('up_user_balance')->insertGetId($data4);
                            //更新司机余额,运费+定金
                            $money = $info['order_dzxy_freight']+$info['order_dzxy_yf'];
                            Db::table('up_u_user')->where('user_id',$info['order_dirver_user'])->setInc('user_balance',$money);
                            //插入加盟商钱包明细
                            $order_number1 = date('YmdHis') . str_pad(mt_rand(1, 99999999), 6, '0', STR_PAD_LEFT).$info['order_jms_user'];
                            $user_real_name1 = Db::table('up_u_user')
                                ->where('user_id',$info['order_dirver_user'])
                                ->value("user_real_name");
                            $data2['user_id'] = $info['order_jms_user'];
                            $data2['balance_type'] = 2;
                            $data2['balance_time'] = date('Y-m-d H:i:s');
                            $data2['balance_title'] = "支付司机".($user_real_name1).'支付运费';
                            $data2['balance_num'] = $order_number1;
                            $data2['balance_price'] = $info['order_dzxy_freight'];
                            $data2['balance_status'] = 2;
                            $data2['balance_xs'] = 2;
                            $data2['balance_jia_jian'] = 2;
                            Db::table('up_user_balance')->insertGetId($data2);
                        }
                    }
                    if($info1['balance_id']!=''){//充值
                        if($info1['balance_status']==1){
                            $result['balance_status'] = 2;
                            $result['order_paytime'] = $getInfo['gmt_payment'];
                            Db::table('up_user_balance')->where('balance_num',$num)->update($result);
                            Db::table('up_u_user')->where('user_id',$info1['user_id'])->setInc('user_balance',$info1['balance_price']);
                        }
                    }


                    Db::commit();
                    die('success');
                }catch (\Exception $e) {
                    Db::rollback();
                    return 'error';
                }
            }
        }
    }
}